﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InductBase;
using SharpBolt.Graphics;
using SharpBolt.Time;

namespace SharpBolt.Tweening
{
    public class Animator
    {
        public enum PartialKey
        {
            ScaleKey, ScaleKeyX, ScaleKeyY,
            PositionKey, PositionKeyX, PositionKeyY,
            RotationKey,
            ShiftKey, ShiftKeyX, ShiftKeyY,
            ColorKey
        };


        public struct AnimationKey
        {
            public Transformation Transformation;
            public DColor DColor;
        }

        public bool Looped;

        public List<PartialKey> PartialKeys;

        internal bool guaranteedEnded = true;
        internal int importance = 0;

        internal EasingDelegate easing;

        internal WeakReference graphicInstanceReference;

        internal GraphicInstance GraphicInstance
        {
            get
            {

                GraphicInstance instance = graphicInstanceReference.Target as GraphicInstance;
                if (instance != null)
                {
                    return instance;
                }
                else
                {
                    return GraphicInstance.EmptyInstance;
                }
            }
            set
            {
                graphicInstanceReference = new WeakReference(value);
            }
        }

        internal Timer Timer;

        internal AnimationKey AnimationKeyA;
        internal AnimationKey AnimationKeyB;

        public void SetCurrentPart(double part)
        {
            Timer.CurrentPart = part;
        }

        public AnimationKey GetAnimationKey()
        {
            double part = Timer.CurrentPart;
            return GetKeyByPart(part);
        }

        public bool IsEnded()
        {
            return Timer.IsEnded;
        }

        public event Action Ended;
        public void OnEnded()
        {
            if (Ended != null)
            {
                Ended();
            }
        }

        public AnimationKey GetKeyByPart(double part)
        {
            AnimationKey result = new AnimationKey();
            if (easing != null) part = easing(part);

            result.DColor = DColor.LinearTween(AnimationKeyA.DColor, AnimationKeyB.DColor, part);
            result.Transformation = Transformation.LinearTween(AnimationKeyA.Transformation, AnimationKeyB.Transformation, part);

            return result;
        }

        public AnimationKey GetEndKey()
        {
            return GetKeyByPart(1);
        }

        public AnimationKey GetStartKey()
        {
            return GetKeyByPart(0);
        }

        internal void Drop()
        {
            Timer.CurrentPart = 1;
            Timer.Drop();
            Ended = null;
        }
    }
}
